import Vue from 'vue'
import Router from 'vue-router'
import store from '@/store/index'
import wechatAuth from '@/utils/wechatAuth'
import VueCookies from 'vue-cookies'

Vue.use(Router)

// const home = r => require.ensure([], () => r(require('@/views/Home/Home')), 'Home')

const routes = [
  {
    path: '*',
    redirect: '/',
  },
  {
    path: '/',
    name: 'home',
    component: () => import(/* webpackChunkName: "Home" */ '@/views/Home/Home.vue'),
    meta: {
      title: '辉派美学研习社',
    },
  },
  {
    path: '/test',
    name: 'test',
    component: () => import(/* webpackChunkName: "Test" */ '@/components/Video.vue'),
    meta: {
      title: '辉派美学研习社',
    },
  },
  {
    path: '/lesson',
    name: 'lesson',
    component: () => import(/* webpackChunkName: "Lesson" */ '@/views/Lesson/Lesson.vue'),
    meta: {
      title: '已购买课程',
    },
  },
  {
    path: '/mine',
    name: 'mine',
    component: () => import(/* webpackChunkName: "Mine" */ '@/views/Mine/Mine.vue'),
    meta: {
      title: '我的',
    },
  },
  {
    path: '/mycollection',
    name: 'mycollection',
    component: () => import(/* webpackChunkName: "MyCollection" */ '@/views/MyCollection/MyCollection.vue'),
    meta: {
      title: '我的收藏',
    },
  },
  {
    path: '/mydiscount',
    name: 'mydiscount',
    component: () => import(/* webpackChunkName: "MyDiscount" */ '@/views/MyDiscount/MyDiscount.vue'),
    meta: {
      title: '我的优惠券',
    },
  },
  {
    path: '/extensioncenter',
    name: 'extensioncenter',
    component: () => import(/* webpackChunkName: "ExtensionCenter" */ '@/views/ExtensionCenter/ExtensionCenter.vue'),
    meta: {
      title: '推广中心',
    },
  },
  {
    path: '/accumulateduser',
    name: 'accumulateduser',
    component: () => import(/* webpackChunkName: "AccumulatedUser" */ '@/views/AccumulatedUser/AccumulatedUser.vue'),
    meta: {
      title: '累积客户',
    },
  },
  {
    path: '/extensionorder',
    name: 'extensionorder',
    component: () => import(/* webpackChunkName: "ExtensionOrder" */ '@/views/ExtensionOrder/ExtensionOrder.vue'),
    meta: {
      title: '推广订单',
    },
  },
  {
    path: '/turntrue',
    name: 'turntrue',
    component: () => import(/* webpackChunkName: "TurnTrue" */ '@/views/TurnTrue/TurnTrue.vue'),
    meta: {
      title: '我的账户',
    },
  },
  {
    path: '/detailofaccount',
    name: 'detailofaccount',
    component: () => import(/* webpackChunkName: "DetailOfAccount" */ '@/views/DetailOfAccount/DetailOfAccount.vue'),
    meta: {
      title: '我的账户',
    },
  },
  {
    path: '/detailofextension',
    name: 'detailofextension',
    component: () =>
      import(/* webpackChunkName: "DetailOfExtension" */ '@/views/DetailOfExtension/DetailOfExtension.vue'),
    meta: {
      title: '我的账户',
    },
  },
  {
    path: '/moreboom',
    name: 'moreboom',
    component: () => import(/* webpackChunkName: "MoreBoom" */ '@/views/MoreBoom/MoreBoom.vue'),
    meta: {
      title: '爆款推荐',
    },
  },
  {
    path: '/detailofboom',
    name: 'detailofboom',
    component: () => import(/* webpackChunkName: "DetailOfBoom" */ '@/views/DetailOfBoom/DetailOfBoom.vue'),
    meta: {
      title: '专栏',
    },
  },
  {
    path: '/detailofvedio',
    name: 'detailofvedio',
    component: () => import(/* webpackChunkName: "DetailOfVedio" */ '@/views/DetailOfVedio/DetailOfVedio.vue'),
    meta: {
      title: '视频',
    },
  },
  {
    path: '/detailofpic',
    name: 'detailofpic',
    component: () => import(/* webpackChunkName: "DetailOfPic" */ '@/views/DetailOfPic/DetailOfPic.vue'),
    meta: {
      title: '图文',
    },
  },
  {
    path: '/search',
    name: 'search',
    component: () => import(/* webpackChunkName: "Search" */ '@/views/Search/Search.vue'),
    meta: {
      title: '搜索',
    },
  },
  {
    path: '/free',
    name: 'free',
    component: () => import(/* webpackChunkName: "FreeActivity" */ '@/views/FreeActivity/Free.vue'),
    meta: {
      title: '赠送视频',
    },
  },
]

// add route path
routes.forEach(route => {
  route.path = route.path || '/' + (route.name || '')
})

const router = new Router({
  routes,
})

const IS_LOGIN = 2
const NO_AUTHORIZATION = 1
const NO_LOGIN = 0
const EXPIRES = '7d'

router.beforeEach((to, from, next) => {
  const title = to.meta && to.meta.title
  if (title) {
    document.title = title
  }

  // TODO:换 cookies 方式记录授权状态

  // localStorage 保存记录状态，BUG：更换微信，更新公众号，获取不到身份信息
  let loginStatus = ~~VueCookies.get('loginStatus') || NO_LOGIN
  if (process.env.NODE_ENV === 'development') loginStatus = IS_LOGIN

  store.commit('setLoginStatus', loginStatus)

  if (store.state.loginStatus === NO_LOGIN) {
    // 微信未授权登录跳转到授权登录页面
    if (router.mode === 'hash') {
      const url = window.location.href.split('#')
      localStorage.setItem('historyUrl', url[1])
      wechatAuth.redirectUri = url[0]
    } else if (router.mode === 'history') {
      wechatAuth.redirectUri = window.location.href
    }

    store.dispatch('setLoginStatus', NO_AUTHORIZATION)
    VueCookies.set('loginStatus', NO_AUTHORIZATION, EXPIRES)
    window.location.href = wechatAuth.authUrl
  } else if (store.state.loginStatus === NO_AUTHORIZATION) {
    try {
      wechatAuth.returnFromWechat(location.search)
    } catch (err) {
      store.dispatch('setLoginStatus', NO_LOGIN)
      next()
    }
    store
      .dispatch('loginWechatAuth', wechatAuth.code)
      .then(res => {
        if (res.errcode === 0 && res.data.sign) {
          store.dispatch('setLoginStatus', IS_LOGIN)
          VueCookies.set('loginStatus', IS_LOGIN, EXPIRES)
          VueCookies.set('wx_sign', res.data.sign, EXPIRES)
          localStorage.setItem('wx_sign', res.data.sign)
          localStorage.setItem('sign_expire', res.data.EXPIRES)
          const url = localStorage.getItem('historyUrl')
          localStorage.removeItem('historyUrl')
          window.location.href = window.location.href.split('?')[0] + '#' + url
        } else {
          store.dispatch('setLoginStatus', NO_LOGIN)
        }
        localStorage.setItem('author_refush_time', true)
        next()
      })
      .catch(err => {
        console.warn(err)
        localStorage.setItem('author_refush_time', true)
        next()
      })
  } else {
    // next('/login')
    next()
  }
})

function judgeWechatAuthUrl() {
  if (router.mode === 'hash') {
    const url = window.location.href.split('#')
    localStorage.setItem('historyUrl', url[1])
    wechatAuth.redirectUri = url[0]
  } else if (router.mode === 'history') {
    wechatAuth.redirectUri = window.location.href
  }
  window.location.href = wechatAuth.authUrl
}

export default router
